package com.teemor.tim.processor.session;

import com.alibaba.fastjson.JSON;
import com.teemor.tim.TencentIMHelper;
import com.teemor.tim.bean.form.cs.TransferCsForm;
import com.teemor.tim.bean.form.openim.SendMsgForm;
import com.teemor.tim.enums.EventEnum;
import com.teemor.tim.enums.MessageType;
import com.teemor.tim.enums.UserStateEnum;
import com.teemor.tim.enums.UserType;
import com.teemor.tim.model.event.EventModel;
import com.teemor.tim.model.message.MessageModel;
import com.teemor.tim.model.message.impl.CustomMessage;
import com.teemor.tim.model.message.impl.TextMessage;
import com.teemor.tim.model.user.UserStateModel;
import com.teemor.tim.processor.CustomerServiceProcessor;
import com.teemor.tim.cache.UserStateCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/12/17 15:30
 */
@Component
public class DefaultCustomerServiceProcessor implements CustomerServiceProcessor {

    @Autowired
    private TencentIMHelper tencentIMHelper;
    @Autowired
    private UserStateCache userStateCache;

    private static final String NOT_FLAG = "NOT_USER";

    @Override
    public void selectSeat(String userId) {
        List<UserStateModel> customerServiceList = userStateCache.getStates(UserType.CUSTOMER_SERVICE);
        if (CollectionUtils.isEmpty(customerServiceList)) {
            this.notifyResult(userId, NOT_FLAG);
            return;
        }
        UserStateModel cs = null;
        UserStateModel userStateModel = userStateCache.getState(userId);
        if (userStateModel == null) {
            userStateModel = new UserStateModel(userId, UserStateEnum.Login.name(), UserType.USER.name());
            userStateCache.cacheState(userStateModel);
        }
        if (CollectionUtils.isEmpty(userStateModel.getSessionUsers())) {
            cs = userStateCache.getState(UserType.CUSTOMER_SERVICE);
            cs.getSessionUsers().add(userStateModel);
            userStateModel.getSessionUsers().add(cs);
        } else {
            cs = userStateModel.getSessionUsers().get(0);
        }
        //通知客服和用户分配结果
        this.notifyResult(userId, cs.getUserId());
    }

    @Override
    public void transferSeat(TransferCsForm form) {
        UserStateModel userStateModel =userStateCache.getState(form.getUserId());
        UserStateModel toCs = userStateCache.getState(form.getToCsId());
        UserStateModel fromCs =  userStateCache.getState(form.getFromCsId());

        //移除用户和原客服的会话
        fromCs.getSessionUsers().remove(userStateModel);
        userStateModel.getSessionUsers().remove(fromCs);

        //简历用户和新客服的会话
        toCs.getSessionUsers().add(userStateModel);
        userStateModel.getSessionUsers().add(toCs);

        //通知结果
        this.notifyResult(form.getUserId(), toCs.getUserId());
    }

    @Async
    public void notifyResult(String userId, String csId) {
        //通知用户分配的客服信息
        EventModel eventModel = new EventModel();
        eventModel.setKey(EventEnum.CSSESSION.name());
        eventModel.setValue(csId);

        CustomMessage message = new CustomMessage();
        message.setDesc(EventEnum.CSSESSION.name());
        message.setData(JSON.toJSONString(eventModel));
        MessageModel messageModel = new MessageModel(MessageType.TIMCustomElem, message);

        SendMsgForm form = new SendMsgForm();
        form.setForbidCallbackControl(Arrays.asList("ForbidBeforeSendMsgCallback",
                "ForbidAfterSendMsgCallback"));
        form.setToAccount(userId);
        form.setMsgBody(Collections.singletonList(messageModel));
        form.setMsgRandom(new Random().nextInt(8999) + 1000);
        form.setMsgTimeStamp(Long.valueOf(System.currentTimeMillis() / 1000).intValue());
        tencentIMHelper.sendMsg(form);

        if (csId.equals(NOT_FLAG)) return;

        //通知客服分配的用户信息，并拉取信息
        eventModel = new EventModel();
        eventModel.setKey(EventEnum.MESSAGES.name());
        eventModel.setValue(userId);

        message = new CustomMessage();
        message.setDesc(EventEnum.MESSAGES.name());
        message.setData(JSON.toJSONString(eventModel));
        messageModel = new MessageModel(MessageType.TIMCustomElem, message);

        form = new SendMsgForm();
        form.setForbidCallbackControl(Arrays.asList("ForbidBeforeSendMsgCallback",
                "ForbidAfterSendMsgCallback"));
        form.setToAccount(csId);
        form.setMsgBody(Collections.singletonList(messageModel));
        form.setMsgRandom(new Random().nextInt(8999) + 1000);
        form.setMsgTimeStamp(Long.valueOf(System.currentTimeMillis() / 1000).intValue());
        tencentIMHelper.sendMsg(form);


        //打招呼信息
        TextMessage textMessage = new TextMessage();
        textMessage.setText("客服【"+csId+"】为您服务");
        messageModel = new MessageModel(MessageType.TIMTextElem, textMessage);
        form = new SendMsgForm();
        form.setForbidCallbackControl(Arrays.asList("ForbidBeforeSendMsgCallback",
                "ForbidAfterSendMsgCallback"));
        form.setFromAccount(csId);
        form.setToAccount(userId);
        form.setMsgBody(Collections.singletonList(messageModel));
        form.setMsgRandom(Long.valueOf(System.currentTimeMillis() % 1608530000000L).intValue());
        form.setMsgTimeStamp(Long.valueOf(System.currentTimeMillis() / 1000).intValue());
        tencentIMHelper.sendMsg(form);
    }
}
